<template>

    <div class="app-container" v-if="canList">
        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="手机号"
                      v-model="listQuery.entity.imgOrder.mobile">
            </el-input>



            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="客户名"
                      v-model="listQuery.entity.cus.shopName">
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="客户编号"
                      v-model="listQuery.entity.cus.code">
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="店员名"
                      v-model="listQuery.entity.user.name">
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="店员编号"
                      v-model="listQuery.entity.user.code">
            </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="备注标记"
                    v-model="listQuery.entity.imgOrder.info">
          </el-input>


          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="大区总监、区域经理、主管、终端代表"
                    v-model="listQuery.entity.imgOrder.topInfo">
          </el-input>


<!--          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"-->
<!--                    placeholder="终端编号"-->
<!--                    v-model="listQuery.entity.top.code">-->
<!--          </el-input>-->

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="省"
                    v-model="listQuery.entity.user.province">
          </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="市"
                    v-model="listQuery.entity.user.city">
          </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="县"
                    v-model="listQuery.entity.user.county">
          </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="连锁药店"
                    v-model="listQuery.entity.user.shopName">
          </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="连锁名称"
                    v-model="listQuery.entity.user.linkName">
          </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="品名"
                    v-model="listQuery.entity.imgOrder.remark">
          </el-input>

          <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                    placeholder="积分"
                    v-model="listQuery.entity.imgOrder.point">
          </el-input>

            <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                       v-model="listQuery.entity.imgOrder.status"
                       placeholder="状态">
                <el-option v-for="(item,index) in  statusEnum" :key="item" :label="item" :value="index">
                </el-option>
            </el-select>


          <el-select @change='handleFilter'  class="filter-item input" style="width: 130px"
                     v-model="orderParam"
                     placeholder="排序方式">
            <el-option v-for="(item,index) in  orderOptions" :key="index" :label="item.name" :value="item.value">
            </el-option>
          </el-select>

          <el-select @change='handleFilter'  class="filter-item input" style="width: 130px"
                     v-model="orderType"
                     placeholder="升序降序">
            <el-option  label="升序" value="asc">
            </el-option>

            <el-option  label="降序" value="desc">
            </el-option>
          </el-select>


            <el-date-picker
                    class="filter-item input"
                    v-model="listQuery.entity.imgOrder.dates"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>

            <div style="display: inline-block">
                <el-button style="margin-left: 10px;" class="filter-item" type="primary" v-waves icon="el-icon-search"
                           @click="handleFilter">查找
                </el-button>

              <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"
                         @click="handleDownload">导出
              </el-button>

            </div>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
                  style="width: 100%;">
            <el-table-column align="center" label="序号">
                <template slot-scope="scope">
<!--                    <span>{{scope.$index+1}}</span>-->
                    <span>{{scope.row.imgOrder.id}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="头像">
                <template slot-scope="scope">
                    <img style="height: 50%;width: 50%" :src="scope.row.user.avatar">
                </template>
            </el-table-column>

            <el-table-column align="center" label="店员">
                <template slot-scope="scope">
                    <span>{{scope.row.user.name}}-{{scope.row.user.code}}</span>
                </template>
            </el-table-column>

          <el-table-column align="center" label="药店名称">
            <template slot-scope="scope">
              <span>{{scope.row.user.shopName}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="连锁名称">
            <template slot-scope="scope">
              <span>{{scope.row.user.linkName}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="区域">
            <template slot-scope="scope">
              <span>{{scope.row.user.city}}</span>
            </template>
          </el-table-column>

          <el-table-column  align="center" label="客户">
            <template slot-scope="scope">
              <span v-if="scope.row.cus">{{scope.row.cus.name}}-{{scope.row.cus.code}}</span>
            </template>
          </el-table-column>



            <el-table-column align="center" label="手机号">
                <template slot-scope="scope">
                    <span>{{scope.row.imgOrder.mobile}}</span>
                </template>
            </el-table-column>

          <el-table-column align="center" label="积分">
            <template slot-scope="scope">
              <span>{{scope.row.imgOrder.point}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="兑费">
            <template slot-scope="scope">
              <span>{{scope.row.imgOrder.money}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="价值">
            <template slot-scope="scope">
              <span>{{scope.row.imgOrder.price}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="产品">
            <template slot-scope="scope">
              <span>{{scope.row.imgOrder.remark}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="时间">
            <template slot-scope="scope">
              <span>{{scope.row.imgOrder.date}}</span>
            </template>
          </el-table-column>

<!--            <el-table-column align="center" label="药店">-->
<!--                <template slot-scope="scope" v-if="scope.row.cus">-->
<!--                    <span>{{scope.row.cus.shopName}}-{{scope.row.cus.code}}</span>-->
<!--                </template>-->
<!--            </el-table-column>-->

            <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                        <span>
                         <el-tag :type="tagTypes[scope.row.imgOrder.status]">     {{statusEnum[scope.row.imgOrder.status]}}</el-tag>
                    </span>
                </template>
            </el-table-column>


            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope)">详细</el-button>
<!--                    <el-button v-if="canSave" size="mini" type="danger"-->
<!--                               @click="handleDelete(scope)">删除-->
<!--                    </el-button>-->
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container" style="margin-top: 20px">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <el-dialog width="80%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"
                     style='width: 80%; margin-left:50px;'>
              <el-form-item label="用户名" prop="mobile">
                <el-input :disabled="true" v-model="temp.user.name"></el-input>
              </el-form-item>
              <el-form-item label="用户编号" prop="mobile">
                <el-input :disabled="true" v-model="temp.user.code"></el-input>
              </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input :disabled="true" v-model="temp.imgOrder.mobile"></el-input>
                </el-form-item>
              <el-form-item label="积分" prop="mobile">
                <el-input :disabled="true" v-model="temp.imgOrder.point"></el-input>
              </el-form-item>

              <el-form-item label="兑费" prop="mobile">
                <el-input :disabled="true" v-model="temp.imgOrder.money"></el-input>
              </el-form-item>
              <el-form-item label="晒单时间" prop="mobile">
                <el-input  v-model="temp.imgOrder.date"></el-input>
              </el-form-item>

<!--                <el-form-item label="产品" prop="remark">-->
<!--                    <el-input :disabled="true"  type="textarea" v-model="temp.imgOrder.remark"></el-input>-->
<!--                </el-form-item>-->

              <el-card class="box-card" style="margin: 24px 0">
                <div slot="header" class="clearfix">
                  <span>选择产品</span>
                  <el-button @click="addItem" style="float: right; padding: 3px 0" type="text">添加</el-button>
                </div>
                <el-form label-width="50px" :inline="true">


                  <div class="" v-for="(item,index) in temp.imgOrder.items" :key="index">


                    <el-form-item label="产品">
                      <el-select v-model="item.goodsId" filterable placeholder="请选择">
                        <el-option
                            v-for="item in goodsOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="数量">
                      <el-input v-model="item.quantity" style="width: 100px;margin-right: 24px"
                                placeHolder=""></el-input>
                      <el-button @click.prevent="deleteItem(index)">删除</el-button>
                    </el-form-item>


                  </div>



                </el-form>
              </el-card>




                <el-form-item label="状态" prop="status">
                    <el-select  class="filter-item" v-model="temp.imgOrder.status" placeholder="类型">
                        <el-option v-for="(item,index) in  statusEnum" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>

              <el-form-item label="备注标记" prop="mobile" >
                <el-input  v-model="temp.imgOrder.info"></el-input>
              </el-form-item>

                <el-form-item label="产品票据" prop="img">
                    <el-upload
                            :disabled="true"
                            ref="imgUpload"
                            action="http://upload.qiniup.com"
                            :auto-upload="true"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :before-upload="handleUpload"
                            :on-success="handleimgUploadSuccess"
                            :data="qData"
                            :file-list="imgList"
                            :on-remove="handleimgRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>

                <el-dialog :visible.sync="dialogVisible" append-to-body>
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
<!--                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>-->
                <el-button  type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        /*padding-bottom: 20px;*/
    }

    .filter-item {
        margin-bottom: 10px;
    }

    .filter-item.input {
        /*line-height: 60px*/
        margin-right: 10px;
    }
</style>

<script>
    import {list, save, update, remove,info,down} from '@/api/img_order'
    import { all as listAll} from "@/api/link_goods";
    import waves from '@/directive/waves' // 水波纹指令

    import {getToken, domain} from '@/api/qiniu'
    import {listToStrs, strsToList} from '@/utils/imgUtil'

    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                orderParam:'imgOrder.id',
                orderType:'desc',
                orderOptions:[{
                  name:"时间",value:"imgOrder.id"
                },
                {
                  name:'价值', value:'imgOrder.price',
                },
                {
                  name:'积分', value:'imgOrder.point',
                },
                  {
                    name:'兑费', value:'imgOrder.money',
                  }
                ],
                tableKey: 0,
                goodsVoOptions:[],
                list: null,
                total: null,
                listLoading: true,
                listQuery: {
                    json:true,
                    page: 1,
                    limit: 20,
                    entity:{
                        imgOrder:{
                            mobile: null,
                            remark: null,
                            date: null
                        },
                        cus:{

                        },
                        user:{

                        }
                    },


                },
                temp: {
                    imgOrder:{
                        id: null,
                        img: null,
                        mobile: null,
                        remark: null
                    },
                    user:{

                    },
                    cus:{

                    }
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '新增'
                },
                tagTypes: ['info', '', 'warning', 'danger', 'warning'],
                statusEnum:['待审核', '通过', '无效'],
                // 存在图片
                dialogImageUrl: '',
                dialogVisible: false,
                imgList: [],
                rules: {
                    img: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    mobile: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    remark: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }]
                },
                downloadLoading: false,
                qData: {
                    token: '',
                    key: ''
                }
            }
        },
        created() {
            this.getList()
             listAll().then(res => {
               this.goodsVoOptions = res.data
             })
        },
        computed: {
            ...mapGetters([
                'perms'
            ]),
            goodsOptions(){
                if(this.temp.user&&this.goodsVoOptions){
                  return this.goodsVoOptions.filter(vo=>vo.head&&vo.head.name==this.temp.user.linkName).map(vo=>vo.linkGoods)
                }
                return []
            },
            orderDesc(){
              if(!this.orderParam){
                return null
              }
              return this.orderParam + " " + this.orderType
            },
            canSave() {
                return hasAuth(this.perms, 'img:order:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'img:order:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'img:order:update')
            },
            canList() {
                return hasAuth(this.perms, 'img:order:list')
            }
        },
        methods: {
            deleteItem(index){
              this.temp.imgOrder.items.splice(index,1)
            },
            addItem(){
              this.temp.imgOrder.items.push({})
            },
            getList() {
                this.listLoading = true
               this.listQuery.order = this.orderDesc
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片
                this.initQiniu()

                // 存在图片字段转换图片地址显示
                this.initImgUrl()
            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
                this.initImgName()// 图片转换
            },
            resetTemp(row) {

                this.temp = {}
                if (row) {
                    this.temp = JSON.parse(JSON.stringify(row)) // copy obj
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(scope) {
                this.index = scope.$index
                // this.beforeFormShow(scope.row)
                // this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                })
            },
            // 显示将图片名封装成可以展示状态集合
            initImgUrl() {
                this.imgList = strsToList(this.temp.imgOrder.img, domain)
            },
            // 关闭显示窗口 重置图片地址 防止错乱
            resetImgUrl() {
                this.imgList = []
            },
            // 上传或者更新的时候从图片链接中获取图片名字
            initImgName() {
                this.temp.img = listToStrs(this.imgList)
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                // const ids = [this.temp.id]
                const ids = [this.list[this.index].id]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    this.list.splice(this.index, 1)
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(scope) {
                this.index = scope.$index
                info(scope.row.imgOrder.id).then(res => {
                  this.beforeFormShow(res.data)
                  this.dialogStatus = 'update'
                  this.dialogFormVisible = true
                  this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                  })
                })


            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            update(this.temp.imgOrder).then(() => {
                                this.list.splice(this.index, 1, this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                // 存在图片
                this.resetImgUrl()
                this.dialogFormVisible = false
            },
          handleDownload() {
            this.downloadLoading = true
            down(this.listQuery).then(res=>{
              this.downloadLoading = false
            })
          },
            formatJson(jsonData) {
                return jsonData.map(v => {
                    let name = v['user']['name']
                    let code = v['user']['code']
                    let mobile = v['imgOrder']['mobile']
                    let cus = v['cus']['shoName']
                    let status = this.statusEnum[v['imgOrder']['status']]
                    return [name,code,mobile,cus,status]
                })
            },
            // 存在图片
            handleUpload(file) {
                this.qData.key = new Date().valueOf() + file.name
            },
            initQiniu() {
                // 获取七牛配置
                getToken().then(res => {
                    this.qData.token = res.data
                }).catch(error => {
                    console.log(error)
                })
            },
            handleimgUploadSuccess(response, file, fileList) {
                this.imgList.push({name: file.response.key, url: domain + file.response.key})
            }
            ,
            handleimgRemove(file, fileList) {
                for (var fn of this.imgList) {
                    if (fn.name === file.name) {
                        this.imgList.splice(this.imgList.indexOf(fn), 1)
                    }
                }
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            }
        }
    }
</script>
